package com.specialized.auth.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.service.CaptchaService;
import com.specialized.auth.domain.CaptchaVos;
import com.specialized.auth.form.RegisterBody;
import com.specialized.common.core.utils.AESUtils;
import com.specialized.passenger.domain.Coupons;
import com.specialized.passenger.remote.PassengerRemoteService;
import com.specialized.system.RemoteUserService;
import com.specialized.system.domain.SysUser;
import com.specialized.system.model.LoginUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import com.specialized.common.core.constant.CacheConstants;
import com.specialized.common.core.constant.Constants;
import com.specialized.common.core.constant.SecurityConstants;
import com.specialized.common.core.constant.UserConstants;
import com.specialized.common.core.domain.Result;
import com.specialized.common.core.enums.UserStatus;
import com.specialized.common.core.exception.ServiceException;
import com.specialized.common.core.text.Convert;
import com.specialized.common.core.utils.StringUtils;
import com.specialized.common.core.utils.ip.IpUtils;
import com.specialized.common.redis.service.RedisService;
import com.specialized.common.security.utils.SecurityUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.specialized.auth.controller.TokenController.getRemoteId;

/**
 * 登录校验方法
 *
 * @author specialized
 */
@Component
@Log4j2
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private PassengerRemoteService passengerRemoteService;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final String KEY="12345678asdfghjk";

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        Result<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (Result.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 手机号验证码登录
     * @param phonenumber
     * @param logincode
     * @return
     */
    public LoginUser loginCode(String phonenumber, String logincode) {
        if(StringUtils.isAnyBlank(phonenumber,logincode)){
            throw new ServiceException("手机号/验证码必须填写");
        }
        if(phonenumber.length()!=UserConstants.PHONE_NUMBER){
            throw new ServiceException("手机号格式错误");
        }
        if(logincode.length()!=UserConstants.CODE){
            throw new ServiceException("验证码格式错误");
        }
        Result<LoginUser> userResult = remoteUserService.getUserInfoByPhoneNumber(phonenumber);
        LoginUser data = userResult.getData();
        SysUser user = data.getSysUser();
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            recordLogService.recordLogininfor(data.getUsername(), Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(data.getSysUser().getUserName(), Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + data.getSysUser().getUserName() + " 不存在");
        }

        if (Result.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
        }
        String  codes = redisService.getCacheObject(phonenumber.toString());
        if(!redisService.hasKey(phonenumber.toString())){
            throw new ServiceException("请先获取验证码");
        }
        if(!logincode.equals(codes)){
            throw new ServiceException("验证码错误");
        }
        recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "登录成功");
        return data;
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }



    private final ApplicationEventPublisher eventPublisher;

    public SysLoginService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }


    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        //解析加密的用户id
        String decrypt=null;
        try {
            decrypt = AESUtils.decrypt(registerBody.getUserId(), KEY);
        }catch (Exception e){
            throw new ServiceException("注册失败,地址信息被篡改",302);
        }

        Result<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (Result.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }

        //发放优惠券
        if (registerBody.getUserId()!=null&&registerBody.getUserId()!=""){
            createCoupon(decrypt.chars().count());
        }
//        eventPublisher.publishEvent(sysUser);

        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    //发送优惠券
    private void createCoupon(Long userid) {
        log.info(userid);
        DateTime date = DateUtil.date();
        Coupons coupons = new Coupons();
        coupons.setUserId(userid);
        coupons.setCouponTitle("邀请好友优惠券");
        coupons.setStartTime(date);
        coupons.setCouponAmount("10");
        coupons.setCouponId(0L);
        coupons.setCouponStatus(0L);
        coupons.setCreateTime(new Date());
        passengerRemoteService.add(coupons);
    }


    public Result getlogincode(CaptchaVos captchaVo, HttpServletRequest request) {
        captchaVo.setBrowserInfo(getRemoteId(request));
        ResponseModel check = this.captchaService.check(captchaVo);
        if(check.getRepCode()!="0000"){
            return Result.success(check);
        }
        String cacheObject = redisService.getCacheObject(captchaVo.getPhonenumber().toString());
        if(null!=cacheObject){
            throw new ServiceException("请勿重复获取验证码");
        }
        rabbitTemplate.convertAndSend("SEND_CODE",captchaVo.getPhonenumber(),message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
            return message;
        });
        return Result.success(check);
    }


}
